#coding=utf-8
#Boa:FramePanel:PanelPeerLend

import wx

from config import *
from product import *
from MyListCtrl import MyListCtrlPeerHistory

[wxID_PANELPEERLEND, wxID_PANELPEERLENDBTNLENDIN, 
 wxID_PANELPEERLENDBTNLENDOUT, wxID_PANELPEERLENDBTNPAYMENT, 
 wxID_PANELPEERLENDBTNQUIT, wxID_PANELPEERLENDBTNRECEIVE, 
 wxID_PANELPEERLENDBTNSHOWPEER, wxID_PANELPEERLENDTCPEER, 
 wxID_PANELPEERLENDTPEER, 
] = [wx.NewId() for _init_ctrls in range(9)]

class PanelPeerLend(wx.Panel):
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self, id=wxID_PANELPEERLEND, name=u'PanelPeerLend',
              parent=prnt, pos=wx.Point(204, 77), size=wx.Size(991, 659),
              style=wx.TAB_TRAVERSAL)
        self.SetClientSize(wx.Size(983, 625))
        self.SetFont(wx.Font(12, wx.SWISS, wx.NORMAL, wx.BOLD, False,
              u'\u6977\u4f53_GB2312'))
        self.SetBackgroundColour(wx.Colour(183, 209, 173))
        self.SetAutoLayout(True)

        self.tPeer = wx.StaticText(id=wxID_PANELPEERLENDTPEER,
              label=u'\u9009\u62e9\u5355\u4f4d\uff1a', name=u'tPeer',
              parent=self, pos=wx.Point(48, 48), size=wx.Size(96, 14), style=0)

        self.tcPeer = wx.TextCtrl(id=wxID_PANELPEERLENDTCPEER, name=u'tcPeer',
              parent=self, pos=wx.Point(144, 40), size=wx.Size(192, 26),
              style=0, value=u'')

        self.btnShowPeer = wx.Button(id=wxID_PANELPEERLENDBTNSHOWPEER,
              label=u'+', name=u'btnShowPeer', parent=self, pos=wx.Point(336,
              40), size=wx.Size(24, 26), style=0)
        self.btnShowPeer.Bind(wx.EVT_BUTTON, self.OnBtnShowPeerButton,
              id=wxID_PANELPEERLENDBTNSHOWPEER)

        self.btnLendIn = wx.Button(id=wxID_PANELPEERLENDBTNLENDIN,
              label=u'\u65b0\u589e\u501f\u5165', name=u'btnLendIn', parent=self,
              pos=wx.Point(48, 80), size=wx.Size(93, 26), style=0)
        self.btnLendIn.Bind(wx.EVT_BUTTON, self.OnBtnLendInButton,
              id=wxID_PANELPEERLENDBTNLENDIN)

        self.btnLendout = wx.Button(id=wxID_PANELPEERLENDBTNLENDOUT,
              label=u'\u65b0\u589e\u501f\u51fa', name=u'btnLendout',
              parent=self, pos=wx.Point(160, 80), size=wx.Size(93, 26),
              style=0)
        self.btnLendout.Bind(wx.EVT_BUTTON, self.OnBtnLendoutButton,
              id=wxID_PANELPEERLENDBTNLENDOUT)

        self.btnReceive = wx.Button(id=wxID_PANELPEERLENDBTNRECEIVE,
              label=u'\u65b0\u589e\u6536\u6b3e', name=u'btnReceive',
              parent=self, pos=wx.Point(312, 80), size=wx.Size(93, 26),
              style=0)
        self.btnReceive.Bind(wx.EVT_BUTTON, self.OnBtnReceiveButton,
              id=wxID_PANELPEERLENDBTNRECEIVE)

        self.btnPayment = wx.Button(id=wxID_PANELPEERLENDBTNPAYMENT,
              label=u'\u65b0\u589e\u4ed8\u6b3e', name=u'btnPayment',
              parent=self, pos=wx.Point(416, 80), size=wx.Size(93, 26),
              style=0)
        self.btnPayment.Bind(wx.EVT_BUTTON, self.OnBtnPaymentButton,
              id=wxID_PANELPEERLENDBTNPAYMENT)

        self.btnQuit = wx.Button(id=wxID_PANELPEERLENDBTNQUIT,
              label=u'\u5173\u95ed', name=u'btnQuit', parent=self,
              pos=wx.Point(760, 80), size=wx.Size(93, 26), style=0)
        self.btnQuit.Bind(wx.EVT_BUTTON, self.OnBtnQuitButton,
              id=wxID_PANELPEERLENDBTNQUIT)

    def __init__(self, parent):
        self._init_ctrls(parent)
        
        self.myInit()
        
    def myInit(self):
        self.m_peer = None
        
        self.lc = MyListCtrlPeerHistory(self)
        self.lc.SetSize(wx.Size(800, 450))
        self.lc.Move(wx.Point(48, 110))
        #self.lc.refresh()

    def OnBtnShowPeerButton(self, event):
        import DlgPeer
        
        dlg = DlgPeer.DlgPeer(self, True)
        if(dlg.ShowModal() == wx.ID_OK):
            self.m_peer = dlg.m_peer
            self.tcPeer.SetValue(self.m_peer.getValue(self.m_peer.fi_name))
            self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.fi_id)})
            
            title = u'【借】%s' %self.m_peer.getValue(self.m_peer.fi_name)
            book = self.GetParent()
            book.SetPageText(book.GetSelection(), title)
        
    def lendPro(self, lendin=True):
        import DlgSelectPro
        import datetime
        
        dlg = DlgSelectPro.create(self.GetParent(), DlgSelectPro.TypeSale)
        if(dlg.ShowModal() == wx.ID_OK):
            
            date = datetime.datetime.today().date()
            user = Cfg.getCurUser()
            
            list = dlg.getProSaleList()
            for proId,proName,unit,num,price,amount,memo in list:
                
                num = float(num)
                if not lendin:
                    num = -num
                    amount = -float(amount)
                
                proId = int(proId)
                
                cls = CDataPeerLend
                data = {cls.fi_peerId:self.m_peer.getKeyVal(),
                        cls.fi_date:date,
                        cls.fi_proId:proId,
                        cls.fi_proName:proName,
                        cls.fi_unit:unit,
                        cls.fi_num:num,
                        cls.fi_price:price,
                        cls.fi_total:amount,
                        cls.fi_handler:user.getKeyVal(),
                        cls.fi_recorder:user.getKeyVal()}
                        
                obj = CDataPeerLend.factory()
                obj.setMulFieldVal(data)
                obj.insert()
                
                # 更新库存
                CDataProduct.updateOnhand(proId, unit, num)
              
                
    def OnBtnLendInButton(self, event):
        if (self.m_peer is None):
            dlg = wx.MessageDialog(self, u'请先选择对方单位',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        self.lendPro()
        self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.fi_id)})

    def OnBtnLendoutButton(self, event):
        if (self.m_peer is None):
            dlg = wx.MessageDialog(self, u'请先选择对方单位',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        self.lendPro(False)
        self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.fi_id)})
    
    def makeAccountDetail(self, accountId, money):
        import datetime
        
        memo = u'  【会款单：%s】' %self.tcPeer.GetValue()
        cls = CDataAccountDetail
        detail = {cls.COL_ACCOUNTID:accountId,
                cls.COL_DATE:datetime.datetime.today().date(),
                cls.COL_MONEY:money,
                cls.COL_FUNDID:'',
                cls.COL_MEMO:memo,
                cls.COL_TIME:datetime.datetime.now()}
                
        print cls.quickInsert(detail)
                
    def addVoucher(self, pay=True):
        import DlgPeerVoucher
        import datetime
        
        print self.m_peer.getDebt()
        
        dlg = DlgPeerVoucher.DlgPeerVoucher(self)
        if(dlg.ShowModal() == wx.ID_OK):
            money,accountObj,handlerObj = dlg.getInput()
            
            money = float(money)
            if pay:
                money = -money
                   
            cls = CDataPeerFund
            data = {cls.fi_peerId:self.m_peer.getKeyVal(),
                    cls.fi_account:accountObj.getKeyVal(),
                    cls.fi_money:money,
                    cls.fi_date:datetime.datetime.today().date(),
                    cls.fi_handler:handlerObj.getKeyVal(),
                    cls.fi_recorder:Cfg.getCurUser().getKeyVal()}
            
            #cls.fi_memo:
            debt = self.m_peer.getDebt()
            if ( debt+ money == 0.0):
                data[cls.fi_memo] = u'至此以前账目全部结清'
            elif(debt>0.0 and  debt+money < 0.0):
                data[cls.fi_memo] = u'实收金额超出应付总额%.2f' %(debt)
            elif(debt<0.0 and  debt+money > 0.0):
                data[cls.fi_memo] = u'收款金额超出应付总额%.2f' %(debt)
                        
            obj = CDataPeerFund.factory()
            obj.setMulFieldVal(data)
            obj.insert()
            
            if (dlg.checkAccount.GetValue()):
                self.makeAccountDetail(accountObj.getKeyVal(), money)
        
            if (data.has_key(cls.fi_memo)):
                dlg = wx.MessageDialog(self, data[cls.fi_memo],u'提示',wx.OK|wx.ICON_INFORMATION)
                dlg.ShowModal()
                            
    def OnBtnReceiveButton(self, event):
        if (self.m_peer is None):
            dlg = wx.MessageDialog(self, u'请先选择对方单位',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        self.addVoucher(False)
        self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.fi_id)})

    def OnBtnPaymentButton(self, event):
        if (self.m_peer is None):
            dlg = wx.MessageDialog(self, u'请先选择对方单位',u'提示',wx.OK|wx.ICON_ERROR)
            dlg.ShowModal()
            return
        
        self.addVoucher()
        self.lc.refresh({'peerId':self.m_peer.getValue(self.m_peer.fi_id)})

    def doClose(self, doQuit=True):
        if doQuit:
            book = self.GetParent()
            book.DeletePage(book.GetSelection())
        return True
        
    def OnBtnQuitButton(self, event):
        self.doClose()
        
